// types/index.ts - 智能水杯小程序类型定义

// ==================== 基础类型 ====================

/** HTTP响应状态码 */
export type HttpStatusCode = 200 | 201 | 400 | 401 | 403 | 404 | 429 | 500;

/** 标准API响应结构 */
export interface ApiResponse<T = any> {
  status: HttpStatusCode;
  code: string;
  message: string;
  data: T;
  timestamp?: number;
  requestId?: string;
}

/** 分页参数 */
export interface PaginationParams {
  page?: number;
  size?: number;
  sort?: string;
  order?: 'ASC' | 'DESC';
}

/** 分页响应 */
export interface PaginatedResponse<T> {
  items: T[];
  total: number;
  page: number;
  size: number;
  totalPages: number;
  hasNext: boolean;
  hasPrevious: boolean;
}

// ==================== 用户相关类型 ====================

/** 用户信息 */
export interface User {
  id: number;
  username: string;
  email?: string;
  phone?: string;
  nickname?: string;
  avatar?: string;
  gender?: 'MALE' | 'FEMALE' | 'UNKNOWN';
  birthday?: string;
  height?: number; // cm
  weight?: number; // kg
  dailyGoal?: number; // ml
  timezone?: string;
  isActive: boolean;
  lastLoginTime?: string;
  createdAt: string;
  updatedAt: string;
}

/** 用户登录请求 */
export interface LoginRequest {
  phone: string;
  password: string;
  rememberMe?: boolean;
  deviceInfo?: DeviceInfo;
}

/** 用户注册请求 */
export interface RegisterRequest {
  phone: string;
  password: string;
  nickname?: string;
  verificationCode: string;
  inviteCode?: string;
}

/** 微信登录请求 */
export interface WechatLoginRequest {
  code: string; // 微信授权码
  encryptedData?: string;
  iv?: string;
  phoneNumber?: string;
  userInfo?: WechatUserInfo;
}

/** 微信用户信息 */
export interface WechatUserInfo {
  openId: string;
  unionId?: string;
  nickname: string;
  avatar: string;
  gender: number;
  city?: string;
  province?: string;
  country?: string;
}

/** 设备信息 */
export interface DeviceInfo {
  platform: string;
  system: string;
  version: string;
  model: string;
  brand: string;
  language: string;
  pixelRatio: number;
  screenWidth: number;
  screenHeight: number;
}

// ==================== 认证相关类型 ====================

/** JWT Token信息 */
export interface TokenInfo {
  token: string;
  expiresAt: number; // 毫秒时间戳
  refreshToken?: string;
  tokenType: 'Bearer';
}

/** JWT Payload */
export interface JwtPayload {
  sub: string; // 用户ID
  username: string;
  exp: number; // 过期时间戳(秒)
  iat: number; // 签发时间戳(秒)
  scope?: string[];
}

/** 登录响应 */
export interface LoginResponse {
  user: User;
  token: TokenInfo;
  isFirstLogin?: boolean;
  needPhoneVerification?: boolean;
}

// ==================== 设备相关类型 ====================

/** 设备基础信息 */
export interface Device {
  id: number;
  deviceSn: string;
  deviceId: string; // 蓝牙设备ID
  deviceName: string;
  model: string;
  userId: number;
  macAddress: string;
  edrAddress?: string; // EDR地址
  bleAddress?: string; // BLE地址
  deviceToken?: string;
  batteryLevel: number; // 0-100
  currentVolume: number; // ml
  waterTemperature?: number; // 摄氏度
  isOnline: boolean;
  lastSyncTime?: string;
  timezone: string;
  firmwareVersion?: string;
  hardwareVersion?: string;
  bindTime: string;
  lastActiveTime?: string;
  settings?: DeviceSettings;
}

/** 设备设置 */
export interface DeviceSettings {
  reminderEnabled: boolean;
  reminderInterval: number; // 分钟
  temperatureUnit: 'CELSIUS' | 'FAHRENHEIT';
  capacityUnit: 'ML' | 'OZ';
  ledBrightness: number; // 0-100
  autoShutdownTime: number; // 分钟
  drinkingGoalReminder: boolean;
  nightModeEnabled: boolean;
  nightModeStartTime: string; // HH:mm
  nightModeEndTime: string; // HH:mm
}

/** 设备绑定请求 */
export interface DeviceBindRequest {
  userId: number;
  deviceSn: string;
  deviceId: string;
  macAddress: string;
  deviceName: string;
  model?: string;
  batteryLevel?: number;
  currentVolume?: number;
  waterTemperature?: number;
  deviceTimezone?: string;
  deviceToken?: string;
  edrAddress?: string;
  bleAddress?: string;
}

/** 设备状态更新请求 */
export interface DeviceStatusUpdate {
  deviceSn: string;
  batteryLevel?: number;
  currentVolume?: number;
  waterTemperature?: number;
  isOnline?: boolean;
}

// ==================== 饮水记录相关类型 ====================

/** 饮水记录 */
export interface WaterRecord {
  id: number;
  userId: number;
  deviceId?: number;
  amount: number; // ml
  type: WaterType;
  temperature: WaterTemperature;
  recordTime: string;
  notes?: string;
  source: RecordSource;
  mood?: DrinkingMood;
  location?: RecordLocation;
  createdAt: string;
  updatedAt: string;
}

/** 饮水类型 */
export type WaterType = 'WATER' | 'TEA' | 'COFFEE' | 'JUICE' | 'MILK' | 'OTHER';

/** 水温类型 */
export type WaterTemperature = 'COLD' | 'ROOM' | 'WARM' | 'HOT';

/** 记录来源 */
export type RecordSource = 'DEVICE' | 'MANUAL' | 'AUTO' | 'IMPORT';

/** 饮水心情 */
export type DrinkingMood = 'HAPPY' | 'TIRED' | 'THIRSTY' | 'ROUTINE' | 'EXERCISE';

/** 记录位置 */
export interface RecordLocation {
  latitude: number;
  longitude: number;
  address?: string;
  city?: string;
  weather?: WeatherInfo;
}

/** 添加饮水记录请求 */
export interface AddWaterRecordRequest {
  amount: number;
  type?: WaterType;
  temperature?: WaterTemperature;
  recordTime?: string; // ISO时间字符串
  notes?: string;
  deviceId?: number;
  mood?: DrinkingMood;
  location?: RecordLocation;
}

// ==================== 统计相关类型 ====================

/** 统计查询参数 */
export interface StatisticsQuery {
  period: 'day' | 'week' | 'month' | 'year';
  date?: string; // YYYY-MM-DD
  userId?: number;
}

/** 统计数据响应 */
export interface StatisticsData {
  totalAmount: number;
  avgAmount: number;
  completionDays: number;
  completionRate: number; // 0-100
  goal: number;
  period: string;
  hourlyStats?: HourlyStats[];
  dailyStats?: DailyStats[];
  weeklyStats?: WeeklyStats[];
  monthlyStats?: MonthlyStats[];
  typeStats?: TypeStats[];
  trendData?: TrendData;
}

/** 小时统计 */
export interface HourlyStats {
  hour: number; // 0-23
  amount: number;
  goal: number;
  recordCount: number;
}

/** 日统计 */
export interface DailyStats {
  date: string; // YYYY-MM-DD
  amount: number;
  goal: number;
  completionRate: number;
  recordCount: number;
  avgTemperature?: number;
}

/** 周统计 */
export interface WeeklyStats {
  week: number; // 1-52
  weekStart: string; // YYYY-MM-DD
  amount: number;
  goal: number;
  completionRate: number;
}

/** 月统计 */
export interface MonthlyStats {
  month: number; // 1-12
  year: number;
  amount: number;
  goal: number;
  completionRate: number;
}

/** 类型统计 */
export interface TypeStats {
  type: WaterType;
  name: string;
  amount: number;
  percentage: number;
  color?: string;
}

/** 趋势数据 */
export interface TrendData {
  trend: 'up' | 'down' | 'stable';
  changeRate: number; // 变化率百分比
  comparison: string; // 对比说明
}

// ==================== 天气相关类型 ====================

/** 天气信息 */
export interface WeatherInfo {
  temperature: number;
  humidity: number;
  weather: string; // 天气描述
  windSpeed?: number;
  pressure?: number;
  uvIndex?: number;
  city: string;
  updateTime: string;
}

// ==================== HTTP客户端相关类型 ====================

/** HTTP请求方法 */
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';

/** HTTP请求配置 */
export interface RequestConfig {
  url: string;
  method?: HttpMethod;
  data?: any;
  params?: Record<string, any>;
  headers?: Record<string, string>;
  timeout?: number;
  skipAuth?: boolean;
  skipAuthCheck?: boolean;
  skipTokenRefresh?: boolean;
  skipThrottle?: boolean;
  showLoading?: boolean;
  showError?: boolean;
  loadingText?: string;
  cache?: boolean;
  cacheTime?: number;
  retry?: boolean;
  retryTimes?: number;
  retryCount?: number;
  cancelDuplicated?: boolean;
  contentType?: string;
  responseType?: string;
  dataType?: string;
  autoRedirect?: boolean;
}

/** HTTP响应 */
export interface HttpResponse<T = any> {
  data: T;
  status: number;
  statusCode: number;
  headers: Record<string, string>;
  config: RequestConfig;
  throttled?: boolean;
  rateLimited?: boolean;
  retryAfter?: number;
}

/** 错误响应 */
export interface ErrorResponse {
  code: string;
  message: string;
  details?: any;
  timestamp: number;
  path?: string;
  method?: string;
  statusCode: number;
}

// ==================== 缓存相关类型 ====================

/** 缓存项 */
export interface CacheItem<T = any> {
  data: T;
  timestamp: number;
  expiry: number;
  key: string;
}

/** 缓存配置 */
export interface CacheConfig {
  defaultExpiry: number; // 默认过期时间(ms)
  maxSize: number; // 最大缓存条目数
  enabled: boolean;
  storageKey: string;
}

// ==================== 应用配置相关类型 ====================

/** 应用配置 */
export interface AppConfig {
  baseUrl: string;
  apiVersion: string;
  timeout: number;
  enableLog: boolean;
  enableCache: boolean;
  enableMock: boolean;
  env: 'development' | 'staging' | 'production';
  features: FeatureFlags;
}

/** 功能开关 */
export interface FeatureFlags {
  enableWeather: boolean;
  enableReminder: boolean;
  enableDataSync: boolean;
  enableDeviceBinding: boolean;
  enableSocialShare: boolean;
  enableAdvancedStats: boolean;
}

// ==================== 实用工具类型 ====================

/** 可选字段 */
export type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;

/** 必填字段 - 修复循环引用问题 */
export type RequiredFields<T, K extends keyof T> = Omit<T, K> & {
  [P in K]-?: T[P];
};

/** 选择特定字段 */
export type Pick<T, K extends keyof T> = {
  [P in K]: T[P];
};

/** 排除特定字段 */
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

/** Promise包装类型 */
export type AsyncResult<T> = Promise<ApiResponse<T>>;

/** 事件监听器类型 */
export type EventListener<T = any> = (event: T) => void;

/** 生命周期钩子 */
export interface LifecycleHooks {
  onLoad?: () => void;
  onShow?: () => void;
  onHide?: () => void;
  onUnload?: () => void;
}

/** 小程序页面类型扩展 */
export interface PageInstance extends LifecycleHooks {
  data: any;
  setData: (data: Record<string, any>, callback?: () => void) => void;
}

/** 登录状态变更监听器 */
export type AuthStateChangeListener = (isLoggedIn: boolean, user?: User) => void;

// ==================== 导出类型组合 ====================

/** 用户相关类型组合 */
export type UserTypes = {
  User: User;
  LoginRequest: LoginRequest;
  RegisterRequest: RegisterRequest;
  WechatLoginRequest: WechatLoginRequest;
  LoginResponse: LoginResponse;
};

/** 设备相关类型组合 */
export type DeviceTypes = {
  Device: Device;
  DeviceSettings: DeviceSettings;
  DeviceBindRequest: DeviceBindRequest;
  DeviceStatusUpdate: DeviceStatusUpdate;
};

/** 记录相关类型组合 */
export type RecordTypes = {
  WaterRecord: WaterRecord;
  AddWaterRecordRequest: AddWaterRecordRequest;
  StatisticsData: StatisticsData;
  StatisticsQuery: StatisticsQuery;
};

/** HTTP相关类型组合 */
export type HttpTypes = {
  RequestConfig: RequestConfig;
  HttpResponse: HttpResponse;
  ApiResponse: ApiResponse;
  ErrorResponse: ErrorResponse;
};
